import dayjs from 'dayjs';
import { cloneDeep, isObject } from 'lodash';
import { message } from 'ant-design-vue';

//深度合并
export function deepMerge<T = any>(source: any = {}, target: any = {}): T {
  let key: string;
  const res: any = cloneDeep(source);
  for (key in target) {
    res[key] = isObject(res[key]) ? deepMerge(res[key], target[key]) : target[key];
  }
  return res;
}

export function isInIframe() {
  return window.self !== window.top;
}

// 下拉框检索
export const filterOption = (input: string, option: { label: string; value: string | number }) => {
  return !!option.label.toLowerCase()?.includes(input?.trim()?.toLowerCase());
};

// 判断两个数组是否相等，忽略顺序
export function judgeArrResult(arr1: any[], arr2: any[]) {
  let flag = true;
  if (arr1.length !== arr2.length) {
    flag = false;
  } else {
    arr1.forEach((item) => {
      if (arr2.indexOf(item) === -1) {
        flag = false;
      }
    });
  }
  return flag;
}

export function getTime(startTime: string, endTime?: string) {
  if (!startTime) return '0秒';
  const diffTime = endTime ? dayjs(endTime).diff(startTime, 'second') : dayjs().diff(startTime, 'second');
  const h = Math.floor(diffTime / 3600);
  const m = Math.floor((diffTime / 60) % 60);
  const s = Math.floor(diffTime % 60);
  if (h > 0) {
    return `${h}时${m}分${s}秒`;
  } else if (m > 0) {
    return `${m}分${s}秒`;
  } else {
    return `${s}秒`;
  }
}

export const copyTextValue = async (value: string) => {
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(value);
      message.destroy();
      message.success('已复制');
    } catch (error: any) {
      let errorMessage = '无法复制文本';
      if (error instanceof DOMException) {
        if (error.name === 'NotAllowedError') {
          errorMessage = '请在浏览器中允许此网站访问剪贴板';
        } else if (error.name === 'SecurityError') {
          errorMessage = '由于安全策略，无法在当前上下文中复制文本';
        }
      }
      message.error(`${errorMessage}: ${error.message}`);
    }
  } else {
    const textArea = document.createElement('textarea');
    textArea.value = value;
    textArea.style.position = 'absolute';
    textArea.style.opacity = '0';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    message.destroy();
    message.success('已复制');
    return new Promise((res, rej) => {
      document.execCommand('copy') ? res(null) : rej();
      textArea.remove();
    });
  }
};

// 下载
export const download = (blob: Blob, fileName = new Date().getTime() + '') => {
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
};

export function getFileNameFromContentDisposition(contentDisposition: string) {
  const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  const matches = filenameRegex.exec(contentDisposition);
  return matches != null && matches[1] ? matches[1].replace(/['"]/g, '') : null;
}
